package com.ht.common.core.valid;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.ht.common.core.utils.StringUtils;

/**
 * 判断字段值是否在给定范围内
 * @author zmx
 *
 */
public class StrValRangeValidator  implements ConstraintValidator<StrValueRange, String>{
	// 全局变量存放值集合
	private List<String> values = new ArrayList<>();
	/**
	 * 匹配空白字符串
	 */
	private boolean required;

	 @Override
	    public void initialize(StrValueRange constraintAnnotation) {
			// 获取注解中的值
	        String[] strList = constraintAnnotation.values();
			// 赋值给全局变量
	        values = Arrays.stream(strList).collect(Collectors.toList());
		 	required=constraintAnnotation.required();
	    }
	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if(StringUtils.isBlank(value)){
			if(required){
				return false;
			}
			return true;
		}
		return values.contains(value.trim());
	}

}
